package com.bds.snatch;

import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.sql.DataSource;

import com.bds.snatch.system.queue.FetchHtmlConsumer;
import org.apache.log4j.Logger;
import org.nutz.dao.Dao;
import org.nutz.dao.impl.NutDao;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.bds.snatch.model.H2Urls;
import com.bds.snatch.system.h2.H2Server;
import com.bds.snatch.system.mq.RepairLocalMQ;
import com.bds.snatch.system.queue.SnatchConsumer;
import com.bds.snatch.system.task.PortalTask;
import com.bds.snatch.system.task.UrlTask;
import com.bds.snatch.system.util.SpringContextHolder;

@SpringBootApplication
@ComponentScan(basePackages = "com.bds")
@EnableAspectJAutoProxy(exposeProxy = true)
public class StartApp {
	private static Logger logger = Logger.getLogger(StartApp.class);

	public static void main(String[] args) throws Exception {

		ApplicationContext application = SpringApplication.run(StartApp.class, args);
		logger.info("##########spring boot 启动成功##########");
		SpringContextHolder.setApplicationContext(application);
		H2Server.startH2Server();
		Properties properties = new Properties();
		properties.put("url", "jdbc:h2:~/urls");
		properties.put("username", "sa");
		properties.put("password", "");
		properties.put("driver", "org.h2.Driver");
		properties.put("type", "com.alibaba.druid.pool.DruidDataSource");
		properties.put("platform", "h2");
		DataSource ds = DruidDataSourceFactory.createDataSource(properties);
		Dao h2dao = new NutDao(ds);
		h2dao.create(H2Urls.class, false);
		new RepairLocalMQ().doStart(h2dao);
//		 new SnatchMQConsumer().doStart(h2dao);
		//修改为：只对portal任务的监控,模板任务由FetchHtmlConsumer监控
		new SnatchConsumer().doStart(h2dao);
		//解析html任务
		new FetchHtmlConsumer().start();
		ScheduledExecutorService scheduled = Executors.newSingleThreadScheduledExecutor();
		// 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间
		scheduled.scheduleAtFixedRate(new PortalTask(h2dao), 5, 20, TimeUnit.SECONDS);
		//此功能，改为python实现
//		scheduled.scheduleAtFixedRate(new UrlTask(h2dao), 5, 30, TimeUnit.SECONDS);

		logger.info("全部启动完毕");
	}
}
